package com.tengju.data.infrastructure.schedule;

import com.tengju.activity.domain.shared.DateUtil;
import com.tengju.data.application.profit.BonusLogArchiveService;
import com.tengju.data.domain.model.alert.AlertEvent;
import com.tengju.data.domain.model.alert.AlertService;
import com.tengju.data.domain.model.analysis.Row;
import com.tengju.data.domain.model.report.AchievementBonusLogRepository;
import com.tengju.data.domain.shared.CastUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

/**
 * @author chenhang
 * @Date 2021/6/22
 */
@Component
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class BonusLogArchiveJob {

    private final AchievementBonusLogRepository bonusLogRepository;
    private final AlertService alertService;
    private final BonusLogArchiveService bonusLogArchiveService;



    private final String jobName = "业绩奖励记录归档任务";

    @Value("${bonus.log.archive.sleep}")
    private long sleepTime;


    @XxlJob("bonusLogArchiveJob")
    public ReturnT<String> execute(String params) {
        List<Row> rows = bonusLogRepository.listLogTimeWithMonth();
        if (CollectionUtils.isEmpty(rows)) {
            XxlJobLogger.log("没有相关的log记录");
            return ReturnT.SUCCESS;
        }
        for (Row row : rows) {
            try {
                LocalDateTime logTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(CastUtil.castLong(row.getValue("logTime"))), ZoneId.systemDefault());
                Integer month = CastUtil.castInt(row.getValue("month"));
                XxlJobLogger.log("归档记录：logTime:{},month:{}",logTime,month);
                bonusLogArchiveService.archive(logTime,month);
                Thread.sleep(sleepTime);
            } catch (Exception e) {
                log.error("{}, jobError",jobName, e);
                AlertEvent event = new AlertEvent(jobName + "异常");
                event.addItem("任务参数",params);
                event.addItem("异常信息",e.getMessage());
                alertService.alert(event);
            }
        }
        return ReturnT.SUCCESS;
    }

}
